import { IFile, IFiles } from "../typings";

// 获取iframe的url
export const getIframeUrl = (iframeRaw: string) => {
  const shimsUrl = "//unpkg.com/es-module-shims@1.8.0/dist/es-module-shims.js";
  // 判断浏览器是否支持esm ，不支持esm就引入es-module-shims
  const newIframeRaw =
    typeof import.meta === "undefined"
      ? iframeRaw.replace(
          "<!-- es-module-shims -->",
          `<script async src="${shimsUrl}"></script>`
        )
      : iframeRaw;
  return URL.createObjectURL(new Blob([newIframeRaw], { type: "text/html" }));
};

// 根据文件名后缀匹配文件类型
export const getFileType = (name: string) => {
  const suffix = name.split(".").pop() || "";
  if (["js", "jsx"].includes(suffix)) return "javascript";
  if (["ts", "tsx"].includes(suffix)) return "typescript";
  if (["json"].includes(suffix)) return "json";
  if (["css"].includes(suffix)) return "css";
  return "javascript";
};

// 根据文件名称获取当前文件模块内的对应模块
export const getModuleFile = (files: IFiles, moduleName: string) => {
  let _moduleName = moduleName.split("./").pop() || "";
  if (!_moduleName.includes(".")) {
    const realModuleName = Object.keys(files).find((key) =>
      key.split(".").includes(_moduleName)
    );
    if (realModuleName) _moduleName = realModuleName;
  }
  return files[_moduleName];
};

export const jsonToJs = (file: IFile) => {
  const js = `export default ${file.value}`;
  return URL.createObjectURL(
    new Blob([js], { type: "application/javascript" })
  );
};

// css转js
export const cssToJs = (file: IFile) => {
  const uuid = new Date().getTime();
  const renderJs = `
              let stylesheet = document.getElementById('style_${uuid}_${file.name}');
              if (!stylesheet) {
                stylesheet = document.createElement('style')
                stylesheet.setAttribute('id', 'style_${uuid}_${file.name}')
                document.head.appendChild(stylesheet)
              }
              const styles = document.createTextNode(\`${file.value}\`)
              stylesheet.innerHTML = ''
              stylesheet.appendChild(styles)
            `;
  return URL.createObjectURL(
    new Blob([renderJs], { type: "application/javascript" })
  );
};

// 编辑前对代码处理
export const beforeTransformCodeHandler = (filename: string, code: string) => {
  let _code = code;
  // 如果没有引入React，开头添加React引用
  const regexReact = /import\s+React/g;
  // 如果是jsx文件，并且没有引入React，开头添加React引用
  if (
    (filename.endsWith(".jsx") || filename.endsWith(".tsx")) &&
    !regexReact.test(code)
  ) {
    _code = `import React from 'react';\n${code}`;
  }
  return _code;
};

// 最大的序列号
export const maxSequenceTabName = (files: string[]) => {
  const result = files.reduce((max, fileName) => {
    const match = fileName.match(/Comp(\d+)\.tsx/);
    if (match) {
      const sequenceNumber = parseInt(match[1], 10);
      return Math.max(max, sequenceNumber);
    }
    return max;
  }, 0);
  return `Comp${result + 1}.tsx`;
};
